<template>
  <div @click="indexNum = -1">
    <div class="major" style="margin-top: 30px">
      <div class="major-left">专业选择</div>
      <div class="major-right">
        <el-popover
          v-for="(item, index) in majorList"
          :visible="indexNum == index"
          :key="index"
          placement="bottom"
          width="auto"
        >
          <template #reference>
            <div
              class="major-size alitem"
              :class="indexNum === index ? 'active' : ''"
              @click.stop="clickChange(index)"
            >
              <div>{{ item.name }}({{ item.childCount }})&nbsp;</div>
              <el-icon>
                <ArrowDown />
              </el-icon>
            </div>
          </template>
          <el-checkbox v-model="checkAll" @change="handleCheckAllChange"
            >全部</el-checkbox
          >
          <el-checkbox-group
            v-model="tempSelMajors"
            @change="handleCheckedCitiesChange"
            style="display: flex; flex-wrap: wrap; width: 500px"
          >
            <el-checkbox
              v-for="major in item.majors"
              :key="major"
              :value="major"
              >{{ major.name }}</el-checkbox
            >
          </el-checkbox-group>
          <div class="right matop">
            <el-button @click="indexNum = -1">取消</el-button>
            <el-button type="primary" @click="onClickCheckboxConfirm"
              >确定</el-button
            >
          </div>
        </el-popover>
      </div>
    </div>
    <div class="major">
      <div class="major-left">招生类型</div>
      <div class="major-right" style="align-items: flex-start">
        <el-select
          v-model="selectType"
          placeholder="Select"
          style="width: 80px; margin-right: 10px"
          @change="handleChange"
        >
          <el-option
            v-for="item in options"
            :key="item.value"
            :label="item.label"
            :value="item.value"
          />
        </el-select>
        <div class="" v-for="(item, index) in studentType" :key="index">
          <el-button
            @click="getStudentsTtype(item)"
            style="height: 30px; margin-right: 10px"
            :type="majorEnrollTypes.includes(item) ? 'primary' : 'default'"
            :disabled="isButtonDisabled"
            >{{ item }}</el-button
          >
        </div>
        <span style="margin: 0 15px 0 5px; color: #ccc">|</span>
        <el-button
          :type="isShow ? 'primary' : 'default'"
          style="height: 30px; margin-right: 10px"
          @click="addMojoy"
          >新增专业</el-button
        >
      </div>
    </div>
    <div
      class="major"
      style="display: flex; align-items: center; margin-left: 8px"
    >
      <div class="major-left">
        限报要求
        <el-tooltip
          class="box-item"
          effect="dark"
          placement="bottom-start"
          style="width: 1000px; height: 500px"
        >
          <template #content>
            <img
              style="width: 1000px; height: 500px"
              src="../../../../assets/images/desc.png"
              alt=""
            />
          </template>
          <img
            src="https://b.gaokaow.cc/question@2x.png"
            alt=""
            style="width: 14px; height: 14px; margin-left: 1px"
          />
        </el-tooltip>
      </div>
      <div
        class="major-right alitem"
        style="display: flex; align-items: center"
      >
        <el-switch
          v-model="isRestrictColorBW"
          @change="
            changeMajorEnrollTypes('isRestrictColorBW', isRestrictColorBW)
          "
          size="small"
          active-text="色盲色弱"
        />
        <el-switch
          style="margin: 0 15px"
          v-model="isRestrictScore"
          size="small"
          active-text="单科成绩"
          @change="changeMajorEnrollTypes('isRestrictScore', isRestrictScore)"
        />
        <el-switch
          v-model="isRestrictLanguage"
          @change="
            changeMajorEnrollTypes('isRestrictLanguage', isRestrictLanguage)
          "
          size="small"
          active-text="语种要求"
        />
      </div>
    </div>
    <el-row class="matop">
      <el-col :span="12">
        <div class="alitem">
          <!-- <div class="major-left">意向专业</div> -->
          <el-input
            ref="buttonRef"
            v-model="searchKey"
            style="width: 240px"
            placeholder="输入意向专业"
            clearable
            @input="searchKeyInput"
            @focus="isShowSearchPop = true"
            @blur="isShowSearchPop = false"
          >
            <template #prefix>
              <el-icon class="el-input__icon">
                <search />
              </el-icon>
            </template>
          </el-input>
          <div style="margin: 0 6px 0 20px">
            <el-checkbox
              v-model="isAllchecked"
              :label="`考生关注(${props.specialtyData.length})`"
              size="large"
              :disabled="props.specialtyData?.length == 0"
              @change="toggleAll"
            />
          </div>
          <div style="margin-top: 4px">
            <el-popover
              :visible="visible"
              ref="myPopover"
              placement="bottom"
              :width="180"
              v-model:visible="showPopover"
            >
              <span v-if="props.specialtyData.length == 0"
                >暂无关注的意向专业...</span
              >
              <div
                style="display: flex; flex-direction: column"
                v-for="(item, index) in props.specialtyData"
                :key="index"
              >
                <el-checkbox-group v-model="Cities.checkedCities">
                  <el-checkbox
                    @change="changeItem"
                    :value="item"
                    :label="item.professionRealName || item.name"
                    size="large"
                  />
                </el-checkbox-group>
              </div>

              <div
                style="display: flex; justify-content: flex-end"
                v-if="props.specialtyData.length != 0"
              >
                <el-button
                  type="primary"
                  size="small"
                  @mousedown.native="schoolSubmit"
                  >确定</el-button
                >
              </div>

              <template #reference>
                <el-icon
                  @click="visible = !visible"
                  class="el-icon--right"
                  size="16"
                >
                  <ArrowDown />
                </el-icon>
              </template>
            </el-popover>
          </div>
          <div
            v-show="isShowSearchPop && searchList.length > 0"
            class="search-popover"
          >
            <div
              class="curr"
              v-for="(item, index) in searchList"
              @mousedown.native="onClickSearchItem(item, index)"
            >
              <div style="padding: 5px 0">
                {{ index == 0 ? '在筛选条件中搜索 "' + item + '"' : item.name }}
              </div>
              <div
                v-if="index + 1 < searchList.length"
                style="width: 100%; height: 1px; background-color: #eee"
              ></div>
            </div>
          </div>
        </div>
      </el-col>
      <el-col :span="12" v-if="idDrawer">
        <div class="flexend right">
          <div>快速通道</div>
          <div class="alitem" @click="fastTrack(1, '3-1')">
            <el-icon size="20">
              <Memo />
            </el-icon>
            院校库
          </div>
          <div class="alitem" @click="fastTrack(3)">
            <el-icon size="20">
              <Histogram />
            </el-icon>
            分数线
          </div>
          <div class="alitem" @click="fastTrack(4)">
            <el-icon size="20">
              <List />
            </el-icon>
            一分一段
          </div>
          <div class="alitem" @click="fastTrack(5)">
            <el-icon size="20">
              <List />
            </el-icon>
            同分去向
          </div>
        </div>
      </el-col>
    </el-row>

    <Drawertool ref="drawertoolRef" />
  </div>
</template>
<script setup>
import { reactive, ref } from 'vue';
import { allMajor, searchMajorFilling } from '@/api/appv2/appv1.js';
import userSearch from '@/store/modules/searchInfo.js';
import _ from 'lodash';
import bus from '@/utils/bus.js';
// 抽屉
import Drawertool from '@/components/Drawertool/';
// const emit = defineEmits(['changeBlindness', 'changeSingle', 'changeBreeding']);
const emit = defineEmits(['majorEnrollType', 'addMojoyType']);
const drawertoolRef = ref(null);
const isAllchecked = ref(false);
const userSearchVal = userSearch();
const props = defineProps({
  // 学生ID
  studentId: {
    type: Number,
    default: 0,
  },
  // 批次线信息
  batchInfo: {
    type: Object,
    default: {},
  },
  idDrawer: {
    type: Boolean,
  },
  zntbProvinceId: {
    type: Number,
    default: 0,
  },
  zntbScore: {
    type: Number,
    default: 0,
  },
  specialtyData: {
    type: Object,
    default: () => [],
  },
  subjectName: {
    type: String,
    default: '',
  },
});
const Cities = reactive({
  checkedCities: [],
});
const visible = ref(false);

const isRestrictColorBW = ref(false);
const isRestrictScore = ref(false);
const isRestrictLanguage = ref(false);

const options = ref([
  {
    value: '1',
    label: '不限',
  },
  {
    value: '2',
    label: '仅看',
  },
  {
    value: '3',
    label: '不看',
  },
]);
// const selectedValue = ref('1');
const selectType = ref('1');
const majorEnrollTypes = ref([]);
const enrollmentType = ref('');

const isButtonDisabled = ref(true);
const indexNum = ref(-1);
const isShow = ref(false);
const searchList = ref([]); // 模糊搜索数据源
const majorList = ref([]); // 专业筛选数据源
const selMajors = ref([]); // 选中的专业筛选数据
const checkAll = ref(false);

const tempSelMajors = ref([]);

const searchKey = ref(''); // 搜索关键词
const isShowSearchPop = ref(false); // 是否显示搜索pop

const studentType = ref([]); // 专业优先招生类型
bus.on('EnrollmentType', (val) => {
  studentType.value = val;
});

const handleChange = (value) => {
  enrollmentType.value = value;
  if (value === '1') {
    isButtonDisabled.value = true;
    majorEnrollTypes.value = [];
  } else {
    isButtonDisabled.value = false;
    selectType.value = options.value.filter(
      (item) => item.value == value
    )[0].label;
  }
  emit('majorEnrollType', {
    majorEnrollTypes: majorEnrollTypes.value,
    enrollmentType: enrollmentType.value,
  });
};
const getStudentsTtype = (item) => {
  if (majorEnrollTypes.value.includes(item)) {
    // 如果已选中，则移除
    majorEnrollTypes.value = majorEnrollTypes.value.filter((v) => v != item);
  } else {
    // 如果未选中，则添加
    majorEnrollTypes.value.push(item);
  }
  emit('majorEnrollType', {
    majorEnrollTypes: majorEnrollTypes.value,
    enrollmentType: enrollmentType.value,
  });
};

const addMojoy = () => {
  isShow.value = !isShow.value;
  emit('addMojoyType', isShow.value ? '新增专业' : '');
};

// 特殊报考要求筛选
const changeMajorEnrollTypes = (type, val) => {
  bus.emit('changeMajorEnrollTypes', { key: type, val: val });
};
const toggleAll = (val) => {
  // searchArray.value = [];
  let searchArray = [];
  if (val) {
    // 全选操作
    props.specialtyData.forEach((v) => {
      v.isChange = true; // 标记为已选
      if (!Cities.checkedCities.includes(v.code)) {
        Cities.checkedCities.push(v);
      }
    });
    // 将选中的项存储到 selItemArray
    if (Cities.checkedCities.length > 0) {
      Cities.checkedCities.forEach((item) => {
        searchArray.push({
          name: item.name,
          code: item.code,
          type: 'major',
        });
      });
      searchArray = [...userSearchVal.majorArrayList, ...searchArray];
      userSearchVal.saveMajorInfoChange(searchArray);
    }
  } else {
    // 取消全选操作
    // 获取 Cities.checkedCities 中的所有 code
    const checkedCodes = Cities.checkedCities.map((city) => city.code);
    // 过滤 userSearchVal.majorArrayList，移除 code 存在于 checkedCodes 中的项
    userSearchVal.majorArrayList = userSearchVal.majorArrayList.filter(
      (major) => !checkedCodes.includes(major.code)
    );
    Cities.checkedCities = [];
    userSearchVal.saveMajorInfoChange(userSearchVal.majorArrayList);
  }
  visible.value = false;
};

// 删除考生关注选项-专业
const headDeleteItem = (item) => {
  Cities.checkedCities = Cities.checkedCities.filter(
    (v) => v.code !== item.code
  );

  selMajors.value = selMajors.value.filter((v) => v.code !== item.code);
  changeItem();
  saveMajorInfo();
};
//专业筛选
const schoolSubmit = () => {
  if (Cities.checkedCities.length !== props.specialtyData.length) {
    isAllchecked.value = false;
  }
  if (Cities.checkedCities.length > 0) {
    let searchArray = [];
    Cities.checkedCities.forEach((item) => {
      searchArray.push({
        name: item.name,
        code: item.code,
        type: 'major',
      });
    });
    userSearchVal.saveMajorInfoChange(searchArray);
  }
  visible.value = false;
};
const changeItem = () => {
  isAllchecked.value =
    Cities.checkedCities.length === props.specialtyData.length;
};
// 模糊搜索
const searchItem = reactive({
  code: 0,
  name: '',
  type: 'msearch',
});

function getallMajor() {
  const data = {
    studentId: props.studentId,
  };

  if (props.batchInfo.is_batch == 1) {
    data.majorsZK = 1;
  } else {
    data.majorsBK = 1;
  }
  allMajor(data).then((res) => {
    if (res.data) {
      majorList.value = res.data.majorsBK || res.data.majorsZK;
    }
  });
}
getallMajor();

// 搜索输入值改变
const searchKeyInput = _.throttle((val) => {
  if (val.length >= 2) {
    searchMajorFilling({
      search: val,
      pageSize: 1000,
      studentId: props.studentId,
    }).then((res) => {
      // const arrList = res.data.filter(
      //   (item) => item.eduLevelName == props.subjectName
      // );
      searchList.value = res.data;
      searchList.value.splice(0, 0, searchKey.value);
      isShowSearchPop.value = true;
    });
  } else {
    searchList.value = [];
    isShowSearchPop.value = false;
  }
}, 800);

/**
 * 点击全选
 * @param {Boolean} val 是否全选
 */
function handleCheckAllChange(val) {
  if (val) {
    let majors = majorList.value[indexNum.value].majors;
    majors.forEach((item) => {
      let arr = tempSelMajors.value.filter((i) => i.code == item.code);

      // 判断是否已存在
      if (arr.length == 0) {
        tempSelMajors.value.push(item);
      }
    });
  } else {
    let majors = majorList.value[indexNum.value].majors;
    majors.forEach((item) => {
      tempSelMajors.value = tempSelMajors.value.filter(
        (i) => i.code != item.code
      );
    });
  }
}

// 点击单个筛选专业
const handleCheckedCitiesChange = (value) => {
  let item = value[value.length - 1];
  // 判断是否有相同code数据在数组中
  let arr = tempSelMajors.value.filter((i) => i.code == item.code);

  if (arr.length >= 2) {
    // 有相同数据，删除第一个添加的该专业
    let index = tempSelMajors.value.findIndex((i) => i.code == item.code);
    tempSelMajors.value.splice(index, 1);
  }

  checkAllChange();
};

/**
 * 点击专业组
 * @param {Number} val 专业组下标
 */
function clickChange(val) {
  if (indexNum.value == val) {
    indexNum.value = -1;
    return;
  } else {
    indexNum.value = val;
  }

  tempSelMajors.value = JSON.parse(JSON.stringify(selMajors.value));

  checkAllChange();
}

// 全选状态改变
function checkAllChange() {
  // 统计当前专业组下已选中专业数
  let majors = majorList.value[indexNum.value].majors;
  let num = 0;
  majors.forEach((item) => {
    let arr = tempSelMajors.value.filter((i) => i.code == item.code);
    num += arr.length;
  });
  // 判断是否全选
  checkAll.value = num >= majors.length;
}

// 确定筛选条件
function onClickCheckboxConfirm() {
  selMajors.value = tempSelMajors.value;
  indexNum.value = -1;

  saveMajorInfo();
}

/**
 * 点击搜素选项
 * @param {Object} item 专业数据
 * @param {Number} index 下标
 */
function onClickSearchItem(item, index) {
  if (index == 0) {
    // 模糊搜索
    searchItem.name = item;
    saveMajorInfo();
  } else {
    // 精准专业搜索
    let index = selMajors.value.findIndex((i) => i.majorCode == item.majorCode);
    if (index < 0) {
      selMajors.value.push(item);
      saveMajorInfo();
    }
  }

  // 添加后清除搜索数据
  searchKey.value = '';
  searchList.value = [];
  isShowSearchPop.value = false;
}

// 保存专业筛选数据到仓库
function saveMajorInfo() {
  let searchArray = [];
  selMajors.value.forEach((item) => {
    searchArray.push({
      name: item.name,
      code: item.majorCode || item.code,
      type: 'major',
    });
  });

  // 判断是否存在模糊搜索
  if (searchItem.name.length > 0) {
    searchArray.push(searchItem);
  }

  userSearchVal.saveMajorInfoChange(searchArray); // 保存到 store 中
}

/**
 * 删除某条筛选条件
 * @param {Object} item {type:'类型', code:'id', name:'标题'}
 */
// function deleteScreenItem(item) {
//   if (item.type == searchItem.type) {
//     searchItem.name = '';
//   } else {
//     selMajors.value = selMajors.value.filter(
//       (i) => (i.code ? i.code : i.majorCode) != item.code
//     );

//     const select = Cities.checkedCities.map((city) => ({
//       code: city.code,
//       name: city.name,
//       type: 'major',
//     }));
//     const combined = [...selMajors.value, ...select];
//     const uniqueSet = new Set();

//     selMajors.value = combined.reduce((acc, item) => {
//       if (!uniqueSet.has(item.code)) {
//         uniqueSet.add(item.code);
//         acc.push(item);
//       }
//       return acc;
//     }, []);
//   }

//   saveMajorInfo();
// }
// 上面保留了你的 把注释打开把我的删掉就好了
let selMajorsCopy = ref([]);
function deleteScreenItem(item) {
  if (!item.code) {
    item.code = item.majorCode;
  }
  selMajorsCopy.value = JSON.parse(JSON.stringify(selMajors.value));

  selMajorsCopy.value.forEach((i) => {
    if (!i.code) {
      i.code = i.majorCode;
    }
  });

  if (item.type == searchItem.type) {
    searchItem.name = '';
  } else {
    selMajors.value = selMajorsCopy.value.filter((i) => i.code != item.code);
  }

  saveMajorInfo();
}

// 快速通道
const fastTrack = (num, tag) => {
  localStorage.setItem('zntbProvinceId', props.zntbProvinceId);
  localStorage.setItem('zntbScore', props.zntbScore);

  if (num == 1) {
    drawertoolRef.value.handleChangeDrawer(true, '3-1', null, tag);
  } else if (num == 2) {
  } else if (num == 3) {
    drawertoolRef.value.handleChangeDrawer(true, 2, null, 0);
  } else if (num == 4) {
    drawertoolRef.value.handleChangeDrawer(true, 5, null, 1);
  } else if (num == 5) {
    drawertoolRef.value.handleChangeDrawer(true, 5, null, 2);
  }
};

function deleteAll() {
  selMajors.value = [];
  tempSelMajors.value = [];
  searchItem.name = '';
  saveMajorInfo();
}
function closeV() {
  visible.value = false;
}
defineExpose({
  deleteScreenItem,
  deleteAll,
  closeV,
  headDeleteItem,
});
</script>
<style lang="scss" scoped>
.flexend {
  div {
    font-size: 14px;
    font-weight: 400;
    color: #4e5969;
    line-height: 14px;
    margin-right: 20px;
    cursor: pointer;
  }
}
.major-left {
  width: 100px;
  font-size: 14px;
  text-align: center;
  color: #9b9b9b;
}
.major {
  display: flex;
  margin-top: 10px;

  .major-right {
    flex: 1;
    display: flex;
    flex-wrap: wrap;
    align-items: center;

    .major-size {
      font-size: 14px;
      margin-bottom: 12px;
      padding: 4px 16px;
      margin-right: 10px;
      text-align: center;
      border: 1px solid #e5e6eb;
      border-radius: 4px;
      cursor: pointer;
      color: #4e5969;
    }

    .active {
      border: 1px solid #004cf7;
      color: #004cf7;
    }
  }
}

.search-popover {
  position: absolute;
  top: 40px;
  left: 0;
  width: 240px;
  height: 200px;
  overflow: auto;
  background-color: white;
  z-index: 999;
  box-shadow: 0 2px 12px 0 rgba(0, 0, 0, 0.1);
  border-radius: 4px;
  border: 1px solid #c9cdd4;
  padding: 0 10px;
  font-size: 14px;
}
</style>
